from rest_framework import serializers

from backend.utils.base_serializer import BaseSerializer
from backend.utils.custom_fields import CustomDateTimeField, CustomDepartmentStatusFiled
from department.models import Department


class DepartmentBaseSerializer(BaseSerializer):
    create_time = CustomDateTimeField()
    update_time = CustomDateTimeField()
    status = serializers.BooleanField(required=False)


class DepartmentCreateSerializer(DepartmentBaseSerializer):
    parent_id = serializers.IntegerField(required=False)
    parent_name = serializers.StringRelatedField(source="parent.name")

    class Meta:
        model = Department
        fields = ['id', 'name', 'address', 'status', 'remark', 'parent_id', 'parent_name', 'create_time', 'update_time']

    def validate_name(self, value):
        if not (value or value.strip()):
            raise self.custom_validation_error("请填写部门名称")
        return value

    def validate_parent_id(self, value):
        if value is None:
            return value
        try:
            Department.advanced_objects.get(pk=value)
            return value
        except Exception as e:
            raise self.custom_validation_error("父级部门不存在")

    def validate(self, attrs):
        _id = self.request.data.get('id')
        parent_id = self.request.data.get('parent_id')
        if all([_id, parent_id]) and _id == parent_id:
            raise self.custom_validation_error('不能选择当前部门作为自己的上级部门')
        return super(DepartmentCreateSerializer, self).validate(attrs)


class DepartmentExportSerializer(DepartmentBaseSerializer):
    status = CustomDepartmentStatusFiled()
    parent_name = serializers.StringRelatedField(source="parent.name")

    class Meta:
        model = Department
        fields = ['id', 'name', 'address', 'status', 'remark', 'parent_name', 'create_time', 'update_time']

    def to_representation(self, instance):
        data = super(DepartmentExportSerializer, self).to_representation(instance)
        return data
